package com.chen.shopping_manager_api.controller;

import co.elastic.clients.elasticsearch.xpack.usage.Base;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chen.shopping_common.pojo.Admin;
import com.chen.shopping_common.result.BaseResult;
import com.chen.shopping_common.service.AdminService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/admin")
public class AdminController {

    @DubboReference
    private AdminService adminService;

    @Autowired
    private PasswordEncoder encoder;

    @PostMapping("/add")
    public BaseResult addAdmin(@RequestBody Admin admin){
        String password = admin.getPassword();
        String encode = encoder.encode(password);
        admin.setPassword(encode);
        adminService.addAdmin(admin);
        return BaseResult.ok();
    }

    @PutMapping("/update")
    public BaseResult updateAdmin(@RequestBody Admin admin){
        if (StringUtils.hasText(admin.getPassword())){
            String password = admin.getPassword();
            String encode = encoder.encode(password);
            admin.setPassword(encode);
        }
        adminService.updateAdmin(admin);
        return BaseResult.ok();
    }

    @DeleteMapping("/delete")
    public BaseResult deleteAdmin(Long aid){
        adminService.deleteAdmin(aid);
        return BaseResult.ok();
    }

    @GetMapping("/findById")
    public BaseResult findAdminById(Long aid){
        Admin admin = adminService.findAdminById(aid);
        return BaseResult.ok(admin);
    }

    @GetMapping("/search")
    @PreAuthorize("hasAnyAuthority('/admin/search')")
    public BaseResult findAdminByPage(int page,int size){
        Page<Admin> admin = adminService.findAdminByPage(page,size);
        return BaseResult.ok(admin);
    }

    @PutMapping("/updateRoleToAdmin")
    public BaseResult updateRoleToAdmin(Long aid,Long[] rids){
        adminService.updateAdminRole(aid,rids);
        return BaseResult.ok();
    }

    @GetMapping("/getUsername")
    public BaseResult getUsername(){
        //获取会话对象
        SecurityContext context = SecurityContextHolder.getContext();
        //获取认证对象
        Authentication authentication = context.getAuthentication();
        //获取信息封装对象
        UserDetails principal = (UserDetails)authentication.getPrincipal();
        return BaseResult.ok(principal.getUsername());
    }
}
